package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.mapper.OrderSettingMapper;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.*;

@Service(interfaceClass = OrderSettingService.class)
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingMapper orderSettingMapper;

    /**
     * 将预约数据保存到数据库
     * 不能使用一条语句引入的原因是有判断条件
     * @param orderSettings 预约数据
     */
    @Override
    public void importOrderSettings(List<OrderSetting> orderSettings) {
        for (OrderSetting orderSetting : orderSettings) {
            setOrderSettingByExist(orderSetting);
        }
    }

    /**
     * 获取这个月的预约人数
     *
     * @param date 获取整个这个月的头尾
     * @return 用遍历的方法把数据灌进list集合里面
     */
    @Override
    public List<Map> findOrderSettingByMonth(String date) {
        String beginDate = date + "-1";
        String endDate = date + "-31";

        //优化：不是用遍历而是直接从数据库获取到map集合
        List<Map> orderSettingMap = orderSettingMapper.getOrderSettingByMonth(beginDate, endDate);

        return orderSettingMap;
    }

    /**
     * 更新可预约人数
     *
     * @param orderSetting (日期，预约人数)
     */
    @Override
    public void updateReservationsByNewNum(OrderSetting orderSetting) {
        setOrderSettingByExist(orderSetting);
    }

    /**
     * 清理从以本月时间的上个月之前所有的预约记录
     *
     * @param date
     */
    @Override
    public void clearExtraOrderSetting(Date date) throws Exception {
        String formatDate = DateUtils.parseDate2String(date);
        orderSettingMapper.deleteRecordByDate(formatDate);
    }

    /**
     * 将ordersetting先判断该时间表中是否存在，后选择更新还是添加入表中
     * @param orderSetting
     */
    private void setOrderSettingByExist(OrderSetting orderSetting) {
        if(orderSettingMapper.findCountByOrderDate(orderSetting.getOrderDate()) > 0) {
            orderSettingMapper.updateOrderSetting(orderSetting);
        } else {
            orderSettingMapper.addOrderSetting(orderSetting);
        }
    }
}
